package com.lindroy.androidplayer.viewmodel

import androidx.lifecycle.MutableLiveData
import com.lindroy.androidplayer.base.viewmodel.BaseViewModel
import com.lindroy.androidplayer.extensions.request
import com.lindroy.androidplayer.extensions.yes
import com.lindroy.androidplayer.logic.model.ArticleResp
import com.lindroy.androidplayer.logic.model.SearchHotKeyworkResp
import com.lindroy.androidplayer.logic.network2.state.ResultState
import com.lindroy.androidplayer.logic.network2.apiService
import com.lindroy.androidplayer.logic.network2.statecallback.ListDataState

/**
 * @author Lin
 * @date 2021/5/1
 * @function 搜索
 */
class SearchViewModel : BaseViewModel() {

    private var pageNo = 0

    var keyword = ""

    val searchHotKeywordsState: MutableLiveData<ResultState<List<SearchHotKeyworkResp>>> =
        MutableLiveData()

    val searchResultState: MutableLiveData<ListDataState<ArticleResp>> = MutableLiveData()

    fun reqSearchKeywords() {
        request({ apiService.getSearchHotKeyword() }, searchHotKeywordsState)
    }

    fun reqSearchResults(isRefresh: Boolean) {
        isRefresh.yes { pageNo = 1 }
        request({ apiService.getSearchArticles(pageNo, keyword) }, {
            searchResultState.value = ListDataState(
                success = true,
                isRefresh = isRefresh,
                isEmpty = it.isEmpty(),
                hasMore = it.hasMore(),
                isFirstEmpty = isRefresh && it.isEmpty(),
                listData = it.datas
            )
            pageNo++
        }, {
            searchResultState.value = ListDataState(
                success = false,
                isRefresh = isRefresh,
                errMessage = it.errorMsg,
                listData = arrayListOf()
            )
        })

    }
}